<template>
  <div class="menu">
    <SystemSelect :sub-system="subSystem" @selectChange="selectChange">
      <span>{{ translateTitle('Dams.ApplicationInterface.选择行业') }}:</span>
      <el-select v-model="industryValue" multiple :placeholder="translateTitle('Dams.ApplicationInterface.请选择')" @change="industryChange">
        <el-option v-for="item in industryOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </SystemSelect>
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane v-for="item in tabsList" :key="item.name" :label="item.name + translateTitle('Dams.ApplicationInterface.菜单')" :name="item.name">
        <div class="flex">
          <div class="common-head" style="width: 200px">
            <el-button type="primary" @click="addMenu">{{ translateTitle('Dams.ApplicationInterface.新增') }}</el-button>
            <el-button type="primary" @click="exportMenu">{{ translateTitle('Dams.ApplicationInterface.导出') }}</el-button>
            <vui-upload
              ref="fileUploadRef"
              :auto-upload="true"
              class="inline-block"
              :file-name="uploadOptions.name"
              :limit="1"
              :post-data="uploadOptions.postData"
              :show-file-list="false"
              style="margin-left: 12px"
              :url="uploadOptions.url"
              @uploadSuccess="uploadSuccess"
            >
              <el-button type="primary">{{ translateTitle('Dams.ApplicationInterface.导入') }}</el-button>
            </vui-upload>
          </div>
          <div class="common-head flex" style="width: 350px">
            <el-input v-model="submenu" clearable placeholder="菜单名称" size="mini" />
            <div class="ml-3">
              <el-button type="primary" @click="menuSearch(item)">搜索</el-button>
            </div>
          </div>
        </div>
        <vxe-table
          :ref="`xTree_${item.name}${subSystem}`"
          align="center"
          border
          :checkbox-config="tableCheckboxConfig"
          :column-config="{ resizable: true }"
          :data="item.treeData"
          :height="`${getHeight - 177}`"
          highlight-current-row
          highlight-hover-row
          :row-config="{ keyField: 'ID' }"
          :tree-config="tableTreeConfig"
        >
          <vxe-column field="label" :title="translateTitle('Dams.ApplicationInterface.菜单名称')" tree-node type="checkbox" />
          <vxe-column field="LANGUAGE_CODE" :title="translateTitle('Dams.ApplicationInterface.语言类型')" />
          <vxe-column field="TYPENAME" :title="translateTitle('Dams.ApplicationInterface.菜单类型')" />
          <vxe-column field="MENU_URL" :title="translateTitle('Dams.ApplicationInterface.菜单地址')" />
          <vxe-column field="SORT" :title="translateTitle('Dams.ApplicationInterface.菜单排序')" />
          <vxe-column :title="translateTitle('Dams.ApplicationInterface.操作')" width="300">
            <template #default="{ row }">
              <vxe-button v-if="row.MODEL_ID" type="text" @click="editorMenu(row)">{{ translateTitle('Dams.ApplicationInterface.编辑') }}</vxe-button>
              <vxe-button v-if="row.children.length == 0 || filterChildren(row.children).length == 0" type="text" @click="deleteMenu(row, item)">
                {{ translateTitle('Dams.ApplicationInterface.删除') }}
              </vxe-button>
              <vxe-button v-if="row.PID && (row.TYPE == '1' || row.TYPE == '2')" type="text" @click="jumpto(row)">
                {{ translateTitle('Dams.ApplicationInterface.跳转配置') }}
              </vxe-button>
              <vxe-button v-if="row.PID && (row.TYPE == '1' || row.TYPE == '2')" type="text" @click="copy(row, item)">
                {{ translateTitle('Dams.ApplicationInterface.复制') }}
              </vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </el-tab-pane>
    </el-tabs>
    <teleport to="body">
      <VuiModal v-if="dialogTableVisible" v-model="dialogTableVisible">
        <template #title>{{ translateTitle('Dams.ApplicationInterface.导入') }}</template>
        <el-form ref="searchForm" :inline="true" label-position="top" :model="subForm" style="margin-bottom: 10px">
          <el-form-item :label="presentModal.subFormObj.coding.label">
            <el-input
              v-model="subForm[presentModal.subFormObj.coding.value]"
              clearable
              :placeholder="translateTitle('Dams.ApplicationInterface.请输入')"
            />
          </el-form-item>
          <el-form-item :label="presentModal.subFormObj.name.label">
            <el-input
              v-model="subForm[presentModal.subFormObj.name.value]"
              clearable
              :placeholder="translateTitle('Dams.ApplicationInterface.请输入')"
            />
          </el-form-item>
          <el-form-item :label="translateTitle('Dams.ApplicationInterface.是否有效')">
            <el-switch v-model="subForm.ACTIVE_FLAG" active-value="Y" inactive-value="N" />
          </el-form-item>
          <el-form-item style="display: flex; align-items: flex-end">
            <el-button type="primary" @click="searchForm">{{ translateTitle('Dams.ApplicationInterface.查询') }}</el-button>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="flex justify-center p-3 border-t border-gray-100">
            <el-button type="primary" @click="onconfirm">{{ translateTitle('Dams.ApplicationInterface.确定') }}</el-button>
          </div>
        </template>
      </VuiModal>
    </teleport>
    <el-dialog
      v-model="addDialog"
      :close-on-click-modal="false"
      :title="translateTitle('Dams.ApplicationInterface.菜单增改')"
      width="60%"
      @close="close"
    >
      <el-form ref="formDialog" label-width="90px" :model="formDialog" :rules="rules">
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.菜单名称')" prop="MENU_NAME" style="margin-bottom: 22px">
          <el-input v-model="formDialog.MENU_NAME" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.上级菜单')" prop="MENU_CODE" style="margin-bottom: 22px">
          <el-cascader
            ref="myCascader"
            v-model="formDialog.MENU_CODE"
            clearable
            :disabled="type == 'editor' && showSuperior"
            :options="dialogOptions"
            :props="{ checkStrictly: true, value: 'value', label: 'label', emitPath: false }"
            :show-all-levels="false"
            @change="cascaderChange"
          />
        </el-form-item>
        <el-form-item
          v-if="subSystem != 'DAMS'"
          :label="translateTitle('Dams.ApplicationInterface.模块ID')"
          prop="MODEL_ID"
          style="margin-bottom: 22px"
        >
          <el-input v-model="formDialog.MODEL_ID" :disabled="type == 'editor'" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.语言类型')" prop="LANGUAGE_CODE" style="margin-bottom: 22px">
          <!-- <el-input v-model="formDialog.LANGUGE_CODE" /> -->
          <el-select v-model="formDialog.LANGUAGE_CODE" disabled :placeholder="translateTitle('Dams.ApplicationInterface.请选择')">
            <el-option v-for="item in languageOptions" :key="item.LANGUAGE_CODE" :label="item.LANGUAGE_DESC" :value="item.LANGUAGE_CODE" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formDialog.MENU_CODE != 'top' && formDialog.MENU_CODE"
          :label="translateTitle('Dams.ApplicationInterface.菜单类型')"
          style="margin-bottom: 22px"
        >
          <!-- <el-input v-model="formDialog.LANGUGE_CODE" /> -->
          <el-select v-model="formDialog.TYPE" :placeholder="translateTitle('Dams.ApplicationInterface.请选择')">
            <el-option v-for="item in TYPEOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="activeName == 'PDA' || formDialog.TYPE === '0'"
          :label="translateTitle('Dams.ApplicationInterface.菜单地址')"
          style="margin-bottom: 22px"
        >
          <el-input v-model="formDialog.MENU_URL" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.菜单ICON')" style="margin-bottom: 22px">
          <exIcon :info="info" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.菜单排序')" style="margin-bottom: 22px">
          <el-input-number v-model="formDialog.SORT" :label="translateTitle('Dams.ApplicationInterface.描述文字')" :max="999" :min="1" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('formDialog')">{{ translateTitle('Dams.ApplicationInterface.确定') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      v-model="copyDialog"
      :close-on-click-modal="false"
      :title="translateTitle('Dams.ApplicationInterface.复制')"
      width="60%"
      @close="close"
    >
      <div v-loading="copyLoading">
        <!-- <span>{{ translateTitle('Dams.ApplicationInterface.选择要复制的菜单') }}：</span> -->
        <span :style="{ color: 'red' }">选择已有内容的菜单进行复制(当前菜单为新菜单):</span>
        <el-cascader v-model="copyMenu" :options="copyOptions" :show-all-levels="false" />
        <div class="text-center" style="margin-top: 15px">
          <el-button v-loading.fullscreen.lock="copyLoading" type="primary" @click="confirmCopy">
            {{ translateTitle('Dams.ApplicationInterface.确定') }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { Mixin } from '@/common/minxin/Mixin'
  import exIcon from '@ve/layout/extension/components/exIcon.vue'
  import { GFCD } from '@/utils/utils'
  import { getList, download } from '../api/home'
  import debounce from 'lodash/debounce'
  import { componentId } from '@/utils/unique'
  import cloneDeep from 'lodash/cloneDeep'
  import SystemSelect from './systemSelect'
  import isArray from 'lodash/isArray'
  import { translateTitle } from '@/utils/i18n'
  import { ungzip, gzip } from '@/utils/gzip.js'
  export default {
    name: 'PublicMenu',
    components: { exIcon, SystemSelect },
    mixins: [Mixin],
    props: {
      //所属子系统
      // subSystem: {
      //   type: String,
      //   default: '',
      // },
      //接口对象
      portObj: {
        type: Object,
        default: () => {},
      },
      //父组件name
      name: {
        type: String,
        default: '',
      },
      btnFix: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        dialogTableVisible: false,
        copyLoading: false,
        languageOptions: [],
        copyMenu: [],
        copyOptions: [],
        copyDialog: false,
        submenu: '',
        oldList: [],
        info: {
          type: 'exIcon',
          name: 'name',
          value: '',
        },
        rules: {
          MODEL_ID: [{ required: true, message: translateTitle('Dams.ApplicationInterface.请输入模块ID'), trigger: 'blur' }],
          MENU_NAME: [{ required: true, message: translateTitle('Dams.ApplicationInterface.请输入菜单名称'), trigger: 'blur' }],
          MENU_CODE: [{ required: true, message: translateTitle('Dams.ApplicationInterface.请选择上级'), trigger: 'change' }],
          LANGUAGE_CODE: [{ required: true, message: translateTitle('Dams.ApplicationInterface.请选择语言类型'), trigger: 'blur' }],
        },
        TYPEOptions: [
          {
            value: '0',
            label: translateTitle('Dams.ApplicationInterface.系统内置'),
          },
          {
            value: '1',
            label: translateTitle('Dams.ApplicationInterface.拖拉拽生成'),
          },
          {
            value: '2',
            label: translateTitle('Dams.ApplicationInterface.数据大屏'),
          },
          {
            value: '3',
            label: translateTitle('Dams.ApplicationInterface.统计报表'),
          },
        ],
        options: [
          {
            value: 'top',
            label: translateTitle('Dams.ApplicationInterface.顶级菜单'),
            children: [],
          },
        ],
        options1: [
          {
            value: 'top',
            label: translateTitle('Dams.ApplicationInterface.顶级菜单'),
            children: [],
          },
        ],
        dialogOptions: [],
        editorItem: {},
        tableTreeConfig: {
          transform: true,
          rowField: 'ID',
          parentField: 'PID',
          indent: 30,
          // reserve: true,
        },
        activeName: 'PC',
        activeIndex: 0,
        pdaTreeData: [],
        treeData: [],
        addDialog: false,
        formDialog: { SORT: 1, TYPE: '' },
        level: 1,
        type: 'add',
        clientHeight: 0,
        configSetting: {},
        unilineData: {},
        topdaConfig: ['W100', 'X100', 'Y100', 'Z100'],
        uploadOptions: {},
        subSystem: 'WMS',
        tabsList: [],
        industryOptions: [
          { value: '1', label: translateTitle('Dams.ApplicationInterface.标准行业') },
          { value: '2', label: translateTitle('Dams.ApplicationInterface.医药行业') },
          { value: '3', label: translateTitle('Dams.ApplicationInterface.水酒行业') },
        ],
        industryValue: [],
        menusList: [],
        showSuperior: false,
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 100}`
      },
      tabPaneName() {
        return this.subSystem + translateTitle('Dams.ApplicationInterface.菜单')
      },
      tableCheckboxConfig() {
        return {
          labelField: 'label',
          // checkMethod: ({ row }) => {
          //   return row.ID != '100' && row.PID != '100'
          // },
          visibleMethod({ row }) {
            // if (row.PID) {
            //   return row.JUMP == 'Y'
            // } else {
            //   let ids = ['100', 'lpms100', 'lwms100', 'les100', 'wcs100']
            //   return ids.indexOf(row.ID) == -1
            // }
            return row.MENU_NAME && (row.TYPE == '1' || row.TYPE == '2' || !row.PID)
          },
        }
      },
    },
    created() {
      // this.topdaConfig.indexOf
      console.log(this.$route.matched[1].props.default.SUB_SYSTEM)
      let systemOptions = cloneDeep(this.$store.getters['user/apps'])
      let index = systemOptions.findIndex((el) => el.APP_CODE == 'DAMS')
      if (index > -1) {
        systemOptions.splice(index, 1)
      }
      let index1 = systemOptions.findIndex((el) => el.APP_CODE == 'BQMS')
      if (index1 > -1) {
        systemOptions.splice(index1, 1)
      }
      this.subSystem = systemOptions[0].APP_CODE
      if (this.subSystem == 'DAMS') {
        delete this.rules.MODEL_ID
      } else {
        this.rules.MODEL_ID = [{ required: true, message: translateTitle('Dams.ApplicationInterface.请输入模块ID'), trigger: 'blur' }]
      }
      let url = GFCD('dams')
      this.uploadOptions = {
        postData: {
          method: 'dams.page.import',
          data: JSON.stringify({ SYS_CODE: this.subSystem, APP_CODE: this.subSystem }),
        },
        name: 'uploadFile',
        url: `${url.domain}${url.baseUrl}`,
      }
      this.init()
    },
    methods: {
      menuSearch(item) {
        console.log(this.submenu, this.tabsList[0].treeData)
        const pcMenuList = item.treeData
        if (this.submenu) {
          item.treeData = pcMenuList.filter((el) => el.MENU_NAME.includes(this.submenu))
        } else {
          this.getTreeData()
        }
      },
      filterChildren(list) {
        return list.filter((el) => !el.BUSINESS_TYPE)
      },
      translateTitle,
      openModal() {},
      selectChange(val) {
        this.subSystem = val
        this.init()
        this.uploadOptions.postData = {
          method: 'dams.page.import',
          data: JSON.stringify({ SYS_CODE: this.subSystem, APP_CODE: this.subSystem }),
        }
      },
      exportMenu() {
        this.$nextTick(async () => {
          console.log(this.$refs[`xTree_${this.tabsList[this.activeIndex].name}${this.subSystem}`])
          if (this.$refs[`xTree_${this.tabsList[this.activeIndex].name}${this.subSystem}`].getCheckboxRecords().length == 0)
            return this.$baseMessage(translateTitle('Dams.ApplicationInterface.请选择菜单'), 'error')
          let arr = this.$refs[`xTree_${this.tabsList[this.activeIndex].name}${this.subSystem}`].getCheckboxRecords().filter((el) => el.PID)
          let list = []
          arr.forEach((row) => {
            list.push({ MENU_CODE: row.ID })
          })
          let url = GFCD('dams')
          let res = await download(`${url.domain}${url.baseUrl}`, {
            data: JSON.stringify({ SYS_CODE: this.subSystem, MENU: list, APP_CODE: this.subSystem }),
            method: 'dams.page.export',
          })
          let blob = new Blob([res], { type: 'text/xml' })
          let reader = new FileReader()
          reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
          reader.onload = (e) => {
            let a = document.createElement('a')
            a.download = translateTitle('Dams.ApplicationInterface.导出文件') + '_' + new Date().getTime() + '.txt'
            a.href = e.target.result
            a.click()
          }
        })
      },
      getBracketData(str) {
        if (str.indexOf('{') != -1 && str.indexOf('}') != -1) {
          let a1 = /\{(.+?)\}/g //正则获取小括号
          let a2 = str.match(a1).toString() //因为输出的是数组，所以得转化成字符串
          var a3 = a2.replace('{', '') //用空字符替换掉括号
          a3 = a3.replace('}', '')
          console.log(a3) //最终得到括号里面的数字
          return a3
        }
      },
      uploadSuccess(file) {
        let res = file.fileList[0].response
        this.$message({
          type: this.getBracketData(res.msg),
          message: res.msg,
        })
        this.getTreeData()
      },
      async getLanguage() {
        let url = GFCD('dams')
        let res = await getList(`${url.domain}${url.baseUrl}`, {
          data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999 }),
          method: 'dams.language.query',
        })
        this.languageOptions = res.data['dams.language.query'].data
        // console.log(res.data['dams.language.query'].data)
      },
      //根据ID筛选树节点
      filterTreeById(tree, id) {
        // 创建一个新的树形结构
        const filteredTree = isArray(tree) ? { children: [...tree] } : { ...tree }
        let list = []
        // 定义递归函数来筛选树
        function filter(node) {
          if (node.ID == id) {
            list = node
            return
          }
          if (node.children && node.children.length > 0) {
            for (let i = node.children.length - 1; i >= 0; i--) {
              const child = node.children[i]
              // 递归筛选子节点
              filter(child)
            }
          }
        }
        filter(filteredTree)
        return list
      },
      copy(row, item) {
        this.unilineData = row
        this.copyOptions = this.getCopyOptions(item.dialogOptions[0].children)
        this.copyDialog = true
        this.copyLoading = false
      },
      async confirmCopy() {
        this.copyLoading = true
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify({ MENU_CODE: this.copyMenu[1], BUSINESS_TYPE: '1', '#LIMIT#': 1, '#PAGE_SIZE#': 9999, APP_CODE: this.subSystem }),
          method: this.portObj.copy,
        })
        let pageJson = ''
        if (res.data[0]?.PAGE_JSON) {
          pageJson = ungzip(res.data[0].PAGE_JSON)
          pageJson._id = 'page_' + componentId(6)
        }
        // let pageJson = JSON.parse(res.data[0].PAGE_JSON)
        const checkboxTreeNode = this.filterTreeById(this.copyOptions, this.copyMenu[1])
        let compressed = gzip(pageJson)
        let sub = {
          PAGE_JSON: compressed,
          MENU_CODE: this.unilineData.ID,
          LANGUAGE_CODE: this.$store.getters['user/language'],
          APP_CODE: this.subSystem,
          BUSINESS_TYPE: '1',
          BUSINESS_TYPE_NAME: '标准行业',
          MENU_NAME: this.unilineData.label,
          TYPE: checkboxTreeNode.TYPE,
        }
        let res1 = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(sub),
          method: this.portObj.save,
        })
        console.log(res1)
        this.copyMenu = ''
        this.$baseMessage(translateTitle('Dams.ApplicationInterface.复制成功'), 'success')
        this.copyLoading = false
        this.copyDialog = false
        this.getTreeData()
      },
      getCopyOptions(list) {
        console.log(list)
        let arr = cloneDeep(list)
        let newArr = []
        for (let index = 0; index < arr.length; index++) {
          const element = arr[index]
          for (let i = 0; i < element.children.length; i++) {
            const e = element.children[i]
            delete e.children
            e.disabled = false
          }
        }
        console.log(arr)
        arr.forEach((row) => {
          if (row.ID != '100') {
            newArr.push(row)
          }
        })
        return newArr
      },
      editorMenu(row) {
        this.addDialog = true
        this.$nextTick(() => {
          this.$refs.formDialog.resetFields()
          if (this.menusList[this.activeIndex].find((el) => el.PID === row.MODEL_ID)) {
            this.showSuperior = true
          } else {
            this.showSuperior = false
          }
          console.log(this.showSuperior)
          this.editorItem = row
          this.type = 'editor'
          this.info.value = row.MENU_ICON
          this.formDialog.MENU_ICON = row.MENU_ICON
          this.formDialog.MODEL_ID = row.MODEL_ID
          this.formDialog.MENU_CODE = row.PID ? row.PID : 'top'
          this.formDialog.MENU_NAME = row.MENU_NAME
          this.formDialog.SUB_SYSTEM = this.subSystem
          this.formDialog.LANGUAGE_CODE = row.LANGUAGE_CODE
          this.formDialog.TYPE = row.TYPE
          this.formDialog.SORT = row.SORT ? row.SORT : 1
          if (row.PID) {
            //第二级
            this.formDialog.MENU_URL = row.MENU_URL
            this.level = 2
            this.formDialog.MENU_SCODE = this.formDialog.MENU_CODE
            this.formDialog.MENU_LV = '2'
            this.formDialog.id = row.ID
          } else {
            //第一级
            this.formDialog.MENU_LV = '1'
            this.level = 1
            this.formDialog.id = row.ID
          }
        })
      },
      deleteMenu(row) {
        console.log(row)
        this.$confirm(translateTitle('Dams.ApplicationInterface.确定删除'), translateTitle('Dams.ApplicationInterface.提示'), {
          confirmButtonText: translateTitle('Dams.ApplicationInterface.确定'),
          cancelButtonText: translateTitle('Dams.ApplicationInterface.取消'),
          type: 'warning',
        })
          .then(async () => {
            let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
            let method, obj
            method = this.portObj.dele
            obj = { MENU_CODE: row.ID, APP_CODE: this.subSystem }
            if (row.BUSINESS_TYPE) {
              method = 'sysPageServiceImpl.standardDeleteBusinessPageJson'
              obj.BUSINESS_TYPE = row.BUSINESS_TYPE
              obj.MENU_CODE = row.PID
            }
            await getList(url, {
              data: JSON.stringify(obj),
              method: method,
            })
            this.$message({
              type: 'success',
              message: translateTitle('Dams.ApplicationInterface.删除成功') + `!`,
            })
            if (this.activeName == 'second') {
              this.getPdaTree()
            } else {
              this.getTreeData()
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(this.formDialog)
            this.formDialog.SUB_SYSTEM = this.subSystem
            this.formDialog.MENU_ICON = this.info.value
            if (this.formDialog.MENU_CODE == 'top') {
              this.formDialog.MENU_LV = '1'
              this.level = 1
            } else {
              this.formDialog.MENU_URL = this.formDialog.MENU_URL ? this.formDialog.MENU_URL : `page_${componentId(6)}`
              this.level = 2
              this.formDialog.MENU_SCODE = this.formDialog.MENU_CODE
              this.formDialog.MENU_LV = '2'
            }
            this.setData()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      async setData() {
        let method = ''
        let obj = {}
        if (this.type == 'add') {
          if (this.level == 1) {
            method = this.portObj.firstAdd
          } else {
            method = this.portObj.secondAdd
          }
          obj = { ...this.formDialog, TYPE: this.formDialog.TYPE, PAGE_JSON: null, ATTRIBUTION_CODE: this.tabsList[this.activeIndex].name }
        } else {
          if (this.level == 1) {
            method = this.portObj.firstEdit
          } else {
            method = this.portObj.secondEdit
          }
          obj = { ...this.formDialog, TYPE: this.formDialog.TYPE, PAGE_JSON: this.formDialog.PAGE_JSON }
        }
        obj.MENU_CODE = obj.id
        delete obj.id
        obj.APP_CODE = this.subSystem
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(obj),
          method: method,
        })
        console.log(res)
        this.addDialog = false
        this.formDialog = { SORT: 1 }
        this.$message({
          type: 'success',
          message:
            this.type == 'add'
              ? translateTitle('Dams.ApplicationInterface.新增成功') + `!`
              : translateTitle('Dams.ApplicationInterface.修改成功') + `!`,
        })
        this.getTreeData()
      },
      cascaderChange() {
        console.log(this.$refs['myCascader'].getCheckedNodes()[0])
        this.editorItem = this.$refs['myCascader'].getCheckedNodes()[0].data
      },
      handleClick(e) {
        this.activeIndex = e.index
        this.dialogOptions = this.tabsList[this.activeIndex].dialogOptions
      },
      windowResize: debounce(function () {
        console.log('document.documentElement.clientHeight', document.documentElement.clientHeight)
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      jumpto(row) {
        console.log(row)
        if (this.activeIndex == 0) {
          let obj = { ID: row.ID, name: row.MENU_NAME, subSystem: this.subSystem }
          if (row.TYPE == '2') {
            obj.type = 'dataCharts'
          } else {
            obj = { ID: row.ID, name: row.MENU_NAME, subSystem: this.subSystem }
          }
          if (row.BUSINESS_TYPE) {
            obj.ID = row.PID
            obj.industry = row.BUSINESS_TYPE
            obj.industryName = row.BUSINESS_TYPE_NAME
            obj.name = row.MENU_NAME
          }
          let routeUrl = this.$router.resolve({
            path: '/diy',
            query: obj,
          })
          window.open(routeUrl.href, '_blank')
        } else {
          let routeUrl = this.$router.resolve({
            path: '/diy',
            query: { ID: row.ID, name: row.MENU_NAME, subSystem: this.subSystem, type: 'mobile' },
          })
          window.open(routeUrl.href, '_blank')
        }
      },
      close() {
        this.addDialog = false
        this.formDialog = { SORT: 1 }
      },
      addMenu() {
        this.type = 'add'
        this.addDialog = true
        this.formDialog.LANGUAGE_CODE = this.$store.getters['user/language']
        this.formDialog.SORT = 1
      },
      industryChange() {
        this.getTree()
      },
      getTreeData() {
        this.getTree()
      },
      getMenuType(val) {
        let str = ''
        switch (val) {
          case '1':
            str = translateTitle('Dams.ApplicationInterface.拖拉拽生成')
            break
          case '0':
            str = translateTitle('Dams.ApplicationInterface.系统内置')
            break
          case '2':
            str = translateTitle('Dams.ApplicationInterface.数据大屏')
            break
          case '3':
            str = translateTitle('Dams.ApplicationInterface.统计报表')
            break
        }
        return str
      },
      getRecursionTree(list, pid) {
        // if()
        return list.reduce((res, current) => {
          if (current['PID'] === pid) {
            current.children = this.getRecursionTree(list, current['ID'])
            return res.concat(current)
          }
          return res
        }, [])
      },
      getTreeType(item) {
        console.log('item', item)
        item.allPageJson.forEach((r) => {
          r.label = r.BUSINESS_TYPE_NAME
          r.PID = r.MENU_CODE
          r.ID = r.MENU_CODE + r.LANGUAGE_CODE + r.BUSINESS_TYPE
          r.value = r.ID
          r.disabled = true
        })
        let pageJson = []
        item.allMenu.forEach((r) => {
          r.value = r.ID
          r.label = r.MENU_NAME
          r.TYPENAME = this.getMenuType(r.TYPE)
          if (item.allPageJson.find((el) => el.PID == r.ID)) {
            item.allPageJson.find((el) => el.PID == r.ID).TYPE = r.TYPE
            pageJson.push(item.allPageJson.find((el) => el.PID == r.ID))
          }
        })
        item.first = this.getRecursionTree(item.allMenu, '')
        console.log(this.getRecursionTree(item.allMenu, ''))
        let arr = item.allMenu.concat(pageJson)
        arr = arr.sort((a, b) => {
          return a.SORT - b.SORT
        })
        console.log(cloneDeep(arr))
        return arr
      },
      async getTree() {
        console.log(this.activeName, this.activeIndex)
        let unfoldList = []
        if (this.tabsList[this.activeIndex]) {
          if (this.$refs[`xTree_${this.tabsList[this.activeIndex]?.name}${this.subSystem}`]) {
            unfoldList = this.$refs[`xTree_${this.tabsList[this.activeIndex]?.name}${this.subSystem}`]?.getTreeExpandRecords()
            console.log(unfoldList)
          }
        }
        this.tabsList = []
        let BUSINESS_TYPE = ''
        if (isArray(this.industryValue)) {
          BUSINESS_TYPE = this.industryValue.join(',')
        }
        let p = {
          '#LIMIT#': 1,
          '#PAGE_SIZE#': 9999,
          APP_CODE: this.subSystem,
          SUB_SYSTEM: this.subSystem,
          BUSINESS_TYPE: BUSINESS_TYPE,
        }
        let method = this.portObj.query
        p.LANGUAGE_CODE = this.$store.getters['user/language']
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(p),
          method: method,
        })
        console.log(res)
        for (const key in res.data) {
          const element = res.data[key]
          this.tabsList.push({
            name: key,
            treeData: this.getTreeType(element),
            dialogOptions: [
              {
                value: 'top',
                label: translateTitle('Dams.ApplicationInterface.顶级菜单'),
                children: element.first,
              },
            ],
          })
          this.menusList.push(element.allMenu)
        }
        this.oldList = cloneDeep(this.tabsList)
        console.log(this.tabsList)
        if (this.tabsList.length == 1) {
          this.activeName = this.tabsList[0]?.name
          this.activeIndex = 0
        }
        this.dialogOptions = cloneDeep(this.tabsList[this.activeIndex].dialogOptions)
        console.log(this.dialogOptions)
        // this.dialogOptions.forEach((r) => {
        //   r.children.forEach((row) => {
        //     if (row.children && row.children.length > 0) {
        //       row.children = []
        //     }
        //   })
        // })
        this.$nextTick(() => {
          console.log(this.tabsList, this.activeIndex, this.subSystem)
          console.log(this.$refs)
          this.$refs[`xTree_${this.tabsList[this.activeIndex]?.name}${this.subSystem}`].setTreeExpand(unfoldList, true)
        })
      },
      init() {
        this.configSetting = GFCD('dams')
        this.windowResize()
        this.getLanguage()
        this.getTreeData()
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/ve/elements/basic/uiTable/style.scss';
  @import '@/ve/styles/elements.scss';
  .menu {
    padding: 10px;
    overflow-y: auto;
    // display: flex;
    background: #ebeef5;
    .common-head {
      padding: 14px 10px;
    }
    :deep() {
      .vxe-icon--caret-right:before {
        border-top-color: transparent;
        border-right-color: transparent;
        border-bottom-color: transparent;
        border-left-color: #000;
      }
      .el-tabs--border-card > .el-tabs__content {
        padding: 0;
      }
      .el-form-item--small.el-form-item {
        margin-bottom: 22px;
      }
      .vxe-table--render-default .vxe-tree--node-btn {
        color: #2b2323;
      }
    }
  }
</style>
